//
//  LeaderAddInspController.m
//  Estate
//
//  Created by heyong on 16/9/6.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "TableTopStateCell.h"
#import "LeaderAddInspController.h"
#import "DefaineCell.h"
#import "selectBtnCell.h"
#import "PositionTableCell.h"
#import "B_wuLiaoCell.h"
#import "QianDTableCell.h"
#import "OrientationViewController.h"
#import "ScoureCell.h"
#import "DoubleBtnCell.h"

@interface LeaderAddInspController ()
{
    //父级项下标
    NSInteger _inspNum;
    //父级巡检项数组
    NSArray *_groupClassArr;
    //选中的父巡检项Id
    NSString *_perItemId;
    //巡检项id
    NSString *_itemId;
    //流转插入数据
    NSMutableDictionary *_gtatsDic;
    UIButton *_btnView;
}

@property (nonatomic, strong)FMDatabase *db;
@property(strong,nonatomic)NSMutableArray *delImageArray;

// 分值上限
@property (copy, nonatomic) NSString *scoreLimit;

// 当前分值
@property (copy, nonatomic) NSString *score;

@end

@implementation LeaderAddInspController

-(NSMutableArray *)delImageArray{
    if(!_delImageArray){
        _delImageArray=[NSMutableArray arrayWithCapacity:0];
    }
    return _delImageArray;
}


- (FMDatabase *)db{
    if(!_db){
        _db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    }
    return _db;
}
-(TPKeyboardAvoidingTableView *)tableView{
    if(_tableView==nil){
        _tableView=[[TPKeyboardAvoidingTableView alloc]initWithFrame:self.view.bounds];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        [_tableView registerClass:[selectBtnCell class] forCellReuseIdentifier:@"sCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"B_wuLiaoCell" bundle:nil] forCellReuseIdentifier:@"textCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"DefaineCell" bundle:nil] forCellReuseIdentifier:@"defaine"];
        [_tableView registerNib:[UINib nibWithNibName:@"TableTopStateCell" bundle:nil] forCellReuseIdentifier:@"topCell"];
        [_tableView registerClass:[H1_ImagesCell class] forCellReuseIdentifier:kCellIdentifier_H1_ImagesCell];
        [_tableView registerNib:[UINib nibWithNibName:@"ScoureCell" bundle:nil] forCellReuseIdentifier:@"scoureCell"];
        
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}
- (NSMutableArray *)selectedAssetURLs{
    if(!_selectedAssetURLs){
        _selectedAssetURLs=[NSMutableArray array];
    }
    return _selectedAssetURLs;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"检查任务单";
    NSLog(@"该巡检项id:%@",self.prosessId);
    
    //判断是否一键汇总（能否编辑） 存在任务id
    if(self.taskId){
        //返回一键汇总条数
        NSArray *isCount= [LSUtility getTotalByProcessID:self.taskId];
        //未汇总且是本人的记录 而且没同步
        if(isCount.count==0&&[self.inspectUserId isEqualToString:USERID]){
            //判断该条记录是否同步
            BOOL tong=[LSUtility getInspectRecordEditById:self.prosessId];
            //没有同步那就可以编辑
            self.isEdit=tong;
        }
    }else{
        if([self.inspectUserId isEqualToString:USERID]){
            //判断该条记录是否同步
            BOOL tong=[LSUtility getInspectRecordEditById:self.prosessId];
            //没有同步那就可以编辑
            self.isEdit=tong;
        }else
        {
            self.isEdit=NO;
        }
    }
    if(self.isEdit){
        self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"wancheng"] style:UIBarButtonItemStyleDone target:self action:@selector(clickSave)];
    }
    
    _btnView=[[UIButton alloc]init];
    
    self.view.backgroundColor=[UIColor colorWithRed:0.95 green:0.96 blue:0.96 alpha:1.00];
    [self.view addSubview:self.tableView];
    
    _curTweet = [[Tweet alloc] init];
    
    [self initDataSource];
    // 获取分值上限
    if (self.dataDic[@"INSPECT_ITEM_ID"]) {
        self.scoreLimit = [LSUtility getInspectScore:self.dataDic[@"INSPECT_ITEM_ID"]];
    } else {
        self.scoreLimit = @"5";
    }
    //新增 默认额外巡检
    if([self.flag isEqualToString:@"add"]) {
        self.ipqc=@"routine";
    }
    
    //得到项目id
    self.proId= [self getProcessProIdByRecordID:self.taskId];
    
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(refresh:) name:@"RefreshImage_xjzz" object:nil];
}

-(NSString *)getProcessProIdByRecordID:(NSString *)recordId{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sqlStr=[NSString stringWithFormat:@"select pro_id from inspect_process where ID=(select INSPECT_PROCESS_ID from inspect_process_record where inspect_process_id='%@')",recordId];
    FMResultSet *resule=[db executeQuery:sqlStr];
    NSString *ids;
    while ([resule next]) {
        ids=[resule stringForColumn:@"pro_id"];
    }
    [db close];
    return ids;
}
#pragma mark-查询数据
- (void)initDataSource
{
    _groupClassArr=[LSUtility getInspectTimeCategory];
    if(self.prosessId) {
        FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
        [db open];
        
        _gtatsDic= [LSUtility queryInspectRecordById:self.prosessId];
        self.dataDic=_gtatsDic;
        
        if(!self.dataDic){
            NSLog(@"self.dataDic为nil");
        }
        //例行巡检
        if(![self.ipqc isEqualToString:@"extra"]){
            //查询父级类
            NSString *sql_2= [NSString stringWithFormat:@"select * from INSPECT_ITEM where id in (select PARENT_ID from INSPECT_ITEM where id in (select INSPECT_ITEM_ID from INSPECT_PROCESS_RECORD where id='%@'))",self.prosessId];
            FMResultSet *result_2=[db executeQuery:sql_2];
             NSString *grop=@"";
            while ([result_2 next]) {
                grop=[result_2 stringForColumn:@"INSPECT_NAME"];
            }

            //查询巡检项
            NSString *sql_3= [NSString stringWithFormat:@"select inspect_name from INSPECT_ITEM where id in (select INSPECT_ITEM_ID from INSPECT_PROCESS_RECORD where id='%@')",self.prosessId];
            FMResultSet *result_3=[db executeQuery:sql_3];
            NSString *itemName=@"";
            while ([result_3 next]) {
                itemName=[result_3 stringForColumn:@"inspect_name"];
                [self.dataDic setObject:itemName forKey:@"itemName"];
            }
            
            //如果父级为@“”  则为没有子级巡检项 自己为自己的父级
            if([grop isEqualToString:@""]){
                grop=itemName;
            }
            //添加类别
            [self.dataDic setObject:grop forKey:@"class"];
            
            /*
             *额外巡检
             */
        }else{
            //查询标题
            //用户巡检项关联ID INSPECT_USER_ITEM_ID
            NSString *user_item_id=self.dataDic[@"INSPECT_USER_ITEM_ID"];
            NSString *sql_2= [NSString stringWithFormat:@"select INSPECT_ADDTIONAL_NAME from INSPECT_USER_ITEM where id='%@'",user_item_id];
            FMResultSet *result_2=[db executeQuery:sql_2];
            while ([result_2 next]) {
                NSString *itemName=[result_2 stringForColumn:@"INSPECT_ADDTIONAL_NAME"];
                [self.dataDic setObject:itemName forKey:@"itemName"];
            }
        }
        //查询附件
        //不涉及查询5  其它查询2
        NSString *itemState=_gtatsDic[@"INSPECT_RESULT"];
        NSString *fileId=@"";
        
        if([itemState isEqualToString:@"0"]||[itemState isEqualToString:@"1"]){
            fileId=[LSUtility queryInspectStateId:self.prosessId state:@"2"];
        }else{
            fileId=[LSUtility queryInspectStateId:self.prosessId state:@"5"];
        }
        
        NSArray *fileArray=[LSUtility queryAllAttachment:fileId];
        for (NSDictionary *fileDic in fileArray) {
            NSString *fileName=fileDic[@"FILE_NAME"];
            NSString *filePath=[DEF_FILE_PATH stringByAppendingString:
                                [NSString stringWithFormat:@"/%@",fileName]];
            [self.selectedAssetURLs addObject:filePath];
        }
        [self refresh:nil];
        
        [db close];
        
    }else{
        self.dataDic=[NSMutableDictionary dictionary];
        [self.dataDic setObject:USERID forKey:@"INSPECT_USER_ID"];
        [self.dataDic setObject:[LSUtility nowTime] forKey:@"CREATE_TIME"];
        [self.dataDic setObject:@"" forKey:@"class"];
        [self.dataDic setObject:@"" forKey:@"itemName"];
        [self.dataDic setObject:@"" forKey:@"INSPECT_INFO"];
        [self.dataDic setObject:@"" forKey:@"INSPECT_RESULT"];
        [self.dataDic setObject:@"" forKey:@"INSPECT_DESC"];
        [self.dataDic setObject:@"" forKey:@"INSPECT_SCORE"];
    }
}

#pragma mark -图片刷新
- (void)refresh:(id)sender{
    if(self.selectedAssetURLs!=nil){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            self.curTweet.selectedAssetURLs =self.selectedAssetURLs;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:2]] withRowAnimation:UITableViewRowAnimationFade];
            });
        });
    }
}

#pragma mark -保存
- (void)clickSave{
    if(self.score) {
        [self.dataDic setObject:self.score forKey:@"INSPECT_SCORE"];
        
    } else {
        [self.dataDic setObject:DEFISNUL(self.scoreLimit)  forKey:@"INSPECT_SCORE"];
    }

    //新增
    if([self.flag isEqualToString:@"add"]){
        [self saveInspection];
    //执行巡检
    }else if([self.flag isEqualToString:@"modState"]){
        [self addInspection];
    //修改巡检
    }else if ([self.flag isEqualToString:@"mod"]){
        [self updateRecord];
    }
}

#pragma mark - 新增巡检数据
-(void)saveInspection{
    
    if([self.dataDic[@"INSPECT_RESULT"]isEqualToString:@""]){
        [LSUtility showToastWithMessage:@"请给出结论" inView:self.view Andtime:1.];
        return;
    }
    
    if(![self.ipqc isEqualToString:@"extra"]){
        if([self.dataDic[@"class"] isEqualToString:@""]){
            [LSUtility showToastWithMessage:@"请选择巡检类" inView:self.view Andtime:1.];
            return;
        }
        if([self.dataDic[@"itemName"] isEqualToString: @""]){
            [LSUtility showToastWithMessage:@"请选择巡检项" inView:self.view Andtime:1.];
            return;
        }else{
            if([self.dataDic[@"itemName"] isEqualToString:@"请在PC端新增该类下巡检项"]){
                [LSUtility showToastWithMessage:@"请在PC端新增该类下巡检项" inView:self.view Andtime:1.8];
                return;
            }
        }
    }else{
        if([self.dataDic[@"itemName"] isEqualToString: @""]){
            [LSUtility showToastWithMessage:@"请输入检查内容" inView:self.view Andtime:1.];
            return;
        }
        if([self.dataDic[@"INSPECT_INFO"] isEqualToString: @""]){
            [LSUtility showToastWithMessage:@"请输入检查情况" inView:self.view Andtime:1.];
            return;
        }
    }

    
    DBHelper *helper=[DBHelper help];
    
    /*
     *  附件表新增数据
     */
    //巡检记录表id
    NSString *fileId=[NSUUID UUID].UUIDString;
    
    self.curTweet.selectedAssetURLs = [self.curTweet.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
    //循环存入附件表
    if(self.curTweet.selectedAssetURLs.count>0){
        //附件表id
        for (int i=0; i<self.curTweet.selectedAssetURLs.count; i++) {
            NSString *ids=[NSUUID UUID].UUIDString;
            
            NSArray *arr=[self.curTweet.selectedAssetURLs[i] componentsSeparatedByString:@"/"];
            
            NSString *imageName = [arr lastObject];
            //如果数据库存在这张图片就不需要插入
            BOOL is=[LSUtility queryInspectProcessRFileName:imageName fileId:self.prosessId];
            if(is){
                NSLog(@"图片存在");
            }else{
                UIImage *image=[UIImage imageWithContentsOfFile:self.curTweet.selectedAssetURLs[i]];
                
                //存入附件表
                [LSUtility insertAttachmentFromFileID:fileId andTableID:ids andImage:image andType:@"INSPECT_01" andImageName:imageName];
            }
        }
    }
    
    /*
     *  巡检流程记录表新增数据
     */
    //用户巡检项Id
    NSString *userItemId=[[NSUUID UUID]UUIDString];
    
    //初始化插入
    NSDictionary *dic_1=@{
                          @"ID":[NSUUID UUID].UUIDString,
                          @"PRO_ID":self.proId,
                          @"INSPECT_PROCESS_ID":self.taskId,
                          @"INSPECT_USER_ID":USERID,
                          @"INSPECT_ITEM_ID":DEFISNUL(_itemId),
                          @"INSPECT_ITEM_STATE":@"1",
                          @"INSPECT_INFO":@"",
                          @"INSPECT_DESC": @"",
                          @"INSPECT_RESULT":@"",
                          @"INSPECT_SCORE":@"",
                          @"INSPECT_USER_ITEM_ID":userItemId,
                          @"INSPECT_ITEM_RECIFICATE_LEADER":@"",
                          @"INSPECT_RECIFICATE_DESC":@"",
                          @"INSPECT_RECIFICATE_REVIEW_USER":@"1",
                          @"INSPECT_RECIFICATE_REVIRE_SCORE":@"",
                          @"INSPECT_RECIFICATE_REVIEW":@"",
                          @"INSPECT_DO_TIME":@"",
                          @"EXTEND_INFO":@"",
                          @"CREATE_TIME":[LSUtility nowTime],
                          @"CREATE_IP":[LSUtility getIPAddress],
                          @"LOCAL_MODIFY_STATE":@"ADD",
                          @"LOCAL_MODIFY_USER_NAME":@"",
                          @"LOCAL_MODIFY_TIME":@""
                          };
    
    BOOL isOk_01=[helper DataBase:self.db insertKeyValues:dic_1 intoTable:INSPECT_PROCESS_RECORD];
    
    //第二次插入
    //合格不合格添加状态待汇总
    
    /*
     *  巡检流程记录插入状态
     **/
    NSString *UserItemState=@"";
    //如果合格不涉及  修改状态为5 完结
    if([self.dataDic[@"INSPECT_RESULT"] isEqualToString:@"2"]){
        UserItemState=@"5";
    }else{
        UserItemState=@"2";
    }
    
    //延迟1分钟 确保创建时间不一样
    NSDictionary *dic_2=@{
                          @"ID":fileId,
                          @"PRO_ID":self.proId,
                          @"INSPECT_PROCESS_ID":self.taskId,
                          @"INSPECT_USER_ID":USERID,
                          @"INSPECT_ITEM_ID":DEFISNUL(_itemId),
                          @"INSPECT_ITEM_STATE":UserItemState,
                          @"INSPECT_INFO":self.dataDic[@"INSPECT_INFO"],
                          @"INSPECT_DESC": self.dataDic[@"INSPECT_DESC"],
                          @"INSPECT_RESULT":self.dataDic[@"INSPECT_RESULT"],
                          @"INSPECT_SCORE":[self.dataDic[@"INSPECT_SCORE"]isEqualToString:@""]?self.scoreLimit:self.dataDic[@"INSPECT_SCORE"],
                          @"INSPECT_USER_ITEM_ID":userItemId,
                          @"INSPECT_ITEM_RECIFICATE_LEADER":@"",
                          @"INSPECT_RECIFICATE_DESC":@"",
                          @"INSPECT_RECIFICATE_REVIEW_USER":@"1",
                          @"INSPECT_RECIFICATE_REVIRE_SCORE":@"",
                          @"INSPECT_RECIFICATE_REVIEW":@"",
                          @"INSPECT_DO_TIME":@"",
                          @"EXTEND_INFO":@"",
                          @"CREATE_TIME":[LSUtility nowTimeAdd1Sec],
                          @"CREATE_IP":[LSUtility getIPAddress],
                          @"LOCAL_MODIFY_STATE":@"ADD",
                          @"LOCAL_MODIFY_USER_NAME":@"",
                          @"LOCAL_MODIFY_TIME":@""
                          };
    BOOL isOk_02=[helper DataBase:self.db insertKeyValues:dic_2 intoTable:INSPECT_PROCESS_RECORD];
    ;
    if(!isOk_02){
        NSLog(@"提示,添加巡检创建失败 357");
    }
    
    
    /*
     *  用户巡检项表新增
     */
    NSDictionary *dic2=@{
                         @"ID":userItemId,
                         @"INSPECT_PROCESS_ID":self.taskId,
                         @"INSPECT_GROUP_ID":[LSUtility getGroupIdByProcessId:self.taskId],
                         @"INSPECT_USER_ID":USERID,
                         @"INSPECT_USER_TYPE":@"1",
                         @"INSPECT_USER_DESC":@"",
                         @"INSPECT_ITEM_ID":DEFISNUL(_itemId),
                         @"INSPECT_ADDTIONAL_NAME":self.dataDic[@"itemName"],
                         @"INSPECT_DESC":self.dataDic[@"INSPECT_DESC"],
                         @"INSPECT_CURRENT_STATE":UserItemState,
                         @"EXTEND_INFO":@"",
                         @"CREATE_USER_NAME":USERID,
                         @"CREATE_TIME":[LSUtility nowTime],
                         @"CREATE_IP":[LSUtility getIPAddress],
                         @"LOCAL_MODIFY_STATE":@"ADD",
                         @"LOCAL_MODIFY_USER_NAME":@"",
                         @"LOCAL_MODIFY_TIME":@""
                         };
    
    BOOL isOk_03=[helper DataBase:self.db insertKeyValues:dic2 intoTable:INSPECT_USER_ITEM];
    
    if(isOk_01&&isOk_03){
        NSNotification * notice = [NSNotification notificationWithName:@"Refresh_xjzz" object:nil userInfo:nil];
        [[NSNotificationCenter defaultCenter]postNotification:notice];
        
        [self.navigationController popViewControllerAnimated:YES];
        
    }else{
        [MBProgressHUD showError:@"添加失败" toView:self.view];
    }
}

#pragma mark - 保存数据 巡检操作
- (void)addInspection{
    
    if([self.dataDic[@"INSPECT_INFO"] isEqualToString:@""]){
        [LSUtility showToastWithMessage:@"请填写检查情况" inView:self.view Andtime:1];
        return;
    }
    
    NSString *fileID=[NSUUID UUID].UUIDString;
    
    DBHelper *helper=[DBHelper help];
    
    
    //巡检项记录表添加  合格不合格添加待汇总 2
    if([self.dataDic[@"INSPECT_RESULT"] isEqualToString:@"0"]||[self.dataDic[@"INSPECT_RESULT"] isEqualToString:@"1"]){
        NSDictionary *dic=@{
                            @"ID":fileID,
                            @"INSPECT_ITEM_STATE":@"2",
                            @"INSPECT_INFO":self.dataDic[@"INSPECT_INFO"],
                            @"INSPECT_DESC": self.dataDic[@"INSPECT_DESC"],
                            @"INSPECT_RESULT":self.dataDic[@"INSPECT_RESULT"],
                            @"INSPECT_SCORE":[self.dataDic[@"INSPECT_SCORE"]isEqualToString:@""]?self.scoreLimit:self.dataDic[@"INSPECT_SCORE"],
                            @"CREATE_TIME":[LSUtility nowTime],
                            @"CREATE_IP":[LSUtility getIPAddress],
                            @"LOCAL_MODIFY_STATE":@"ADD",
                            };
        
        NSMutableDictionary *dicc=[LSUtility queryInspectRecordById:self.prosessId];
        
        //字典新增其它字典
        [dicc setValuesForKeysWithDictionary:dic];
        //流程记录表新增状态为2 待汇总
        [helper DataBase:self.db insertKeyValues:dicc intoTable:INSPECT_PROCESS_RECORD];
        //如果不涉及添加状态为5 完结
    }else{
        NSDictionary *dic_5=@{
                              @"ID":fileID,
                              @"INSPECT_ITEM_STATE":@"5",
                              @"INSPECT_INFO":self.dataDic[@"INSPECT_INFO"],
                              @"INSPECT_DESC": self.dataDic[@"INSPECT_DESC"],
                              @"INSPECT_RESULT":self.dataDic[@"INSPECT_RESULT"],
                              @"INSPECT_SCORE":[self.dataDic[@"INSPECT_SCORE"]isEqualToString:@""]?self.scoreLimit:self.dataDic[@"INSPECT_SCORE"],
                              @"CREATE_TIME":[LSUtility nowTime],
                              @"CREATE_IP":[LSUtility getIPAddress],
                              @"LOCAL_MODIFY_STATE":@"ADD",
                              };
        NSMutableDictionary *dic_s=[LSUtility queryInspectRecordById:self.prosessId];
        [dic_s setValuesForKeysWithDictionary:dic_5];
        //流程记录表新增状态为结束
        [helper DataBase:self.db insertKeyValues:dic_s intoTable:INSPECT_PROCESS_RECORD];
    }
    
    //附件表新增
    self.curTweet.selectedAssetURLs = [self.curTweet.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
    //循环存入附件表
    if(self.curTweet.selectedAssetURLs.count>0){
        //附件表id
        for (int i=0; i<self.curTweet.selectedAssetURLs.count; i++) {
            NSString *ids=[NSUUID UUID].UUIDString;
            NSArray *arr=[self.curTweet.selectedAssetURLs[i] componentsSeparatedByString:@"/"];
            NSString *imageName = [arr lastObject];
            
            //如果数据库存在这张图片就不需要插入
            BOOL is=[LSUtility queryInspectProcessRFileName:imageName fileId:self.prosessId];
            if(is){
                NSLog(@"图片存在");
            }else{
                UIImage *image=[UIImage imageWithContentsOfFile:self.curTweet.selectedAssetURLs[i]];
                
                //存入附件表
                [LSUtility insertAttachmentFromFileID:fileID andTableID:ids andImage:image andType:@"INSPECT_01" andImageName:imageName];
            }
        }
    }
    
    
    /*
     *  修改用户巡检项的状态
     */
    //得到id
    NSString *usetItemId=_gtatsDic[@"INSPECT_USER_ITEM_ID"];
    //合格不合格  修改状态为待汇总
    if([self.dataDic[@"INSPECT_RESULT"] isEqualToString:@"0"]||[self.dataDic[@"INSPECT_RESULT"] isEqualToString:@"1"]){
        [LSUtility updateInspectUserItembyId:usetItemId andState:2];
    }else{
        [LSUtility updateInspectUserItembyId:usetItemId andState:5];
    }
    
    NSNotification * notice = [NSNotification notificationWithName:@"Refresh_xjzz" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notice];
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark - 待汇总可修改
- (void)updateRecord{
    
    /*
     *  巡检记录表修改数据
     */
    //合格  或者 不合格
    if([self.dataDic[@"INSPECT_RESULT"] isEqualToString:@"0"]||[self.dataDic[@"INSPECT_RESULT"] isEqualToString:@"1"]){
        NSDictionary *dics=@{
                             @"INSPECT_INFO": self.dataDic[@"INSPECT_INFO"],
                             @"INSPECT_DESC":self.dataDic[@"INSPECT_DESC"],
                             @"INSPECT_RESULT":self.dataDic[@"INSPECT_RESULT"],
                             @"INSPECT_SCORE":self.dataDic[@"INSPECT_SCORE"],
                             @"INSPECT_ITEM_STATE":@"2",
                             @"MODIFY_TIME":[LSUtility nowTime],
                             @"MODIFY_IP":[LSUtility getIPAddress],
                             @"LOCAL_MODIFY_STATE":@"ADD",
                             };
        DBHelper *helper=[DBHelper help];
        [helper DataBase:self.db updateTable:INSPECT_PROCESS_RECORD setKeyValues:dics whereCondition:@{@"ID":self.prosessId}];
        //不涉及改为结束
    }else{
        NSDictionary *dics=@{
                             @"INSPECT_INFO": self.dataDic[@"INSPECT_INFO"],
                             @"INSPECT_DESC":self.dataDic[@"INSPECT_DESC"],
                             @"INSPECT_RESULT":self.dataDic[@"INSPECT_RESULT"],
                             @"INSPECT_SCORE":[self.dataDic[@"INSPECT_SCORE"]isEqualToString:@""]?self.scoreLimit:self.dataDic[@"INSPECT_SCORE"],
                             @"INSPECT_ITEM_STATE":@"5",
                             @"MODIFY_TIME":[LSUtility nowTime],
                             @"MODIFY_IP":[LSUtility getIPAddress],
                             @"LOCAL_MODIFY_STATE":@"ADD",
                             };
        DBHelper *helper=[DBHelper help];
        [helper DataBase:self.db updateTable:INSPECT_PROCESS_RECORD setKeyValues:dics whereCondition:@{@"ID":self.prosessId}];
    }
    
    //附件表新增
    self.curTweet.selectedAssetURLs = [self.curTweet.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
    //循环存入附件表
    if(self.curTweet.selectedAssetURLs.count>0){
        //附件表id
        for (int i=0; i<self.curTweet.selectedAssetURLs.count; i++) {
            NSString *ids=[NSUUID UUID].UUIDString;
            NSArray *arr=[self.curTweet.selectedAssetURLs[i] componentsSeparatedByString:@"/"];
            NSString *imageName = [arr lastObject];
            //如果数据库存在这张图片就不需要插入
            BOOL is=[LSUtility queryInspectProcessRFileName:imageName fileId:self.prosessId];
            if(is){
                NSLog(@"图片存在");
            }else{
                UIImage *image=[UIImage imageWithContentsOfFile:self.curTweet.selectedAssetURLs[i]];
                //存入附件表
                [LSUtility insertAttachmentFromFileID:self.prosessId andTableID:ids andImage:image andType:@"INSPECT_01" andImageName:imageName];
            }
        }
    }
    //附件表删除
    //    self.delImageArray=[_delImageArray valueForKeyPath:@"distinctUnionOfObjects.self"];
    if(_delImageArray.count>0){
        for (int i=0; i<_delImageArray.count; i++) {
            NSArray *arr=[_delImageArray[i] componentsSeparatedByString:@"/"];
            NSString *imageName = [arr lastObject];
            //附件表状态改为del
            BOOL isok=[LSUtility delAttachmentForFileId:self.prosessId fileName:imageName];
            if(isok){
                NSLog(@"修改成功");
            }else{
                NSLog(@"修改失败");
            }
        }
    }
    
    //修改用户巡检项状态
    //用户巡检项id
    NSString *usetItemId=_gtatsDic[@"INSPECT_USER_ITEM_ID"];
    
    //判断是否是服务器返回
    
    /*
     *修改用户巡检的状态
     */
    //本地数据
    if(![LSUtility updateIsDown:usetItemId table:INSPECT_USER_ITEM]){
        //合格 不合格  修改状态为待汇总
        if([self.dataDic[@"INSPECT_RESULT"] isEqualToString:@"0"]||[self.dataDic[@"INSPECT_RESULT"] isEqualToString:@"1"]){
            [LSUtility updateInspectUserItembyId:usetItemId andState:2];
        }else{
            [LSUtility updateInspectUserItembyId:usetItemId andState:5];
        }
    }else{
        //合格 不合格  修改状态为待汇总
        if([self.dataDic[@"INSPECT_RESULT"] isEqualToString:@"0"]||[self.dataDic[@"INSPECT_RESULT"] isEqualToString:@"1"]){
            [LSUtility updateInspectUserItembyIdADD:usetItemId andState:2];
        }else{
            [LSUtility updateInspectUserItembyIdADD:usetItemId andState:5];
        }
    }
    
    NSNotification * notica = [NSNotification notificationWithName:@"Refresh_xjzz" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notica];
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma  mrak--UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    long section=indexPath.section;
    long row=indexPath.row;
    //新增页面
    if([self.flag isEqualToString:@"add"]){
        //额外巡检
        if([self.ipqc isEqualToString:@"extra"]){
            if(section==0){
                if(row==0){
                    return 40;
                }
                return 44;
            }else if(section==1){
                if(row==0||row==3||row==5){
                    return 44;
                }else{
                    return 120;
                }
                
            }else{
                return  [H1_ImagesCell cellHeightWithObj:_curTweet title:@"附件"];
            }
        }else{
            if(section==0){
                if(row==0){
                    return 40;
                }
                return 44;
            }else if(section==1){
                if(row==0||row==1||row==4||row==6){
                    return 44;
                }else{
                    return 120;
                }
            }else{
                return  [H1_ImagesCell cellHeightWithObj:_curTweet title:@"附件"];
            }
        }
    }else{
        if(section==0){
            if(row==0){
                return 40;
            }
            return 44;
        }else if(section==1){
            if(row==0||row==3||row==5||row==6){
                return 44;
            }else{
                return 120;
            }
        }else{
            return  [H1_ImagesCell cellHeightWithObj:_curTweet title:@"附件"];
        }
    }
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section==0){
        return 0.001;
    }else{
        return 10;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //新增页面
    if([self.flag isEqualToString:@"add"]){
        if([self.ipqc isEqualToString:@"extra"]){
            if(section==0){
                return 4;
            }else if (section==1){
                return  6;
            }else{
                return 1;
            }
        }else{
            if(section==0){
                return 4;
            }else if (section==1){
                return 7;
            }else{
                return 1;
            }
        }
    }else{
        if(section==0){
            return 4;
        }else if (section==1){
            return 6;
        }else{
            return 1;
        }
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WEAKSELF
    long section=indexPath.section;
    long row=indexPath.row;
    if(section==0){
        if(row==0){
            TableTopStateCell *cell=[tableView dequeueReusableCellWithIdentifier:@"topCell" forIndexPath:indexPath];
            NSString *userId=self.dataDic[@"INSPECT_USER_ID"];
            NSString *name=[LSUtility getuserIdByUserName:userId][@"REAL_NAME"];
            cell.title.text=[NSString stringWithFormat:@"%@%@检查任务单",[LSUtility dateNow],DEFISNUL(name)];
            
            return cell;
            
        }else if(row==1){
            DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
            if(!self.prosessId){
                NSString *proName=[LSUtility getProjectNameByProjectId:self.proId][@"PROJECT_NAME"];
                [cell setTitle:@"项   目:" andDetail:DEFISNUL(proName) andLeftConstraint:20.];
            }else{
                NSString *proid=[LSUtility getProcessProIdByRecordID:self.prosessId];
                NSString *proName=[LSUtility getProjectNameByProjectId:proid][@"PROJECT_NAME"];
                [cell setTitle:@"项   目:" andDetail:DEFISNUL(proName) andLeftConstraint:20.];
            }
            
            return  cell;
            
        }else if(row==2){
            DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
            NSString *userId=self.dataDic[@"INSPECT_USER_ID"];
            NSString *name=[LSUtility getuserIdByUserName:userId][@"REAL_NAME"];
            [cell setTitle:@"记录人:" andDetail:DEFISNUL(name) andLeftConstraint:20.];
            return  cell;
        }else{
            DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
            if(self.isEdit){
                [cell setTitle:@"时   间:" andDetail:[LSUtility nowTime] andLeftConstraint:20.];
            }else{
                [cell setTitle:@"时   间:" andDetail:self.dataDic[@"CREATE_TIME"] andLeftConstraint:20.];
            }
            return  cell;
        }
        
    } else if (section==1){
        if([self.flag isEqualToString:@"add"]){
            //额外巡检
            if([self.ipqc isEqualToString:@"extra"]){
                if(row==0){
                    DoubleBtnCell *cell=[DoubleBtnCell cellWithTableView:tableView];
                    //新增可选择
                    if([self.flag isEqualToString:@"add"]){
                        cell.edit=YES;
                        cell.extraBtn.selected=YES;
                        cell.extraClickBtn=^(){
                            weakSelf.ipqc=@"extra";
                            weakSelf.scoreLimit = @"5";
                            self.score = nil;
                            [weakSelf.tableView reloadData];
                        };
                        
                        cell.rountine=^() {
                            self.scoreLimit = [LSUtility getInspectScore:_itemId];
                            weakSelf.ipqc = @"routine";
                            self.score = nil;
                            [weakSelf.tableView reloadData];
                        };
                    }else{
                        cell.edit=NO;
                        cell.extraBtn.selected=YES;
                    }
                    return cell;
                }else if(row==1){
                    B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                    cell.isEdit=self.isEdit;
                    [cell setTitle:@"检查内容:" andPlaceHolder:@"请输入检查内容" andTextValue:_dataDic[@"itemName"]];
                    [_btnView removeFromSuperview];
                    cell.textValueChangedBlock=^(NSString *value){
                        [self.dataDic setObject:value forKey:@"itemName"];
                    };
                    
                    return cell;
                    
                }else if(row==2){
                    
                    B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                    
                    cell.textValueChangedBlock=^(NSString *value){
                        [self.dataDic setValue:value forKey:@"INSPECT_INFO"];
                    };
                    
                    [cell setTitle:@"检查情况:" andPlaceHolder:@"请输入检查情况" andTextValue:DEFISNUL(self.dataDic[@"INSPECT_INFO"])];
                    
                    cell.isEdit=weakSelf.isEdit;
                    
                    return cell;
                    
                }else if(row==3){
                    
                    selectBtnCell *cell=[tableView dequeueReusableCellWithIdentifier:@"sCell" forIndexPath:indexPath];
                    cell.isEdit=self.isEdit;
                    [cell setTitle:@"结论:" andBtn_1:@"合格" andBtn_2:@"不合格" andBtn_3:@"不涉及"];
                    
                    if([_dataDic[@"INSPECT_RESULT"] isEqualToString:@""]){
                        [cell InspSetBtnType:@"0"];
                        [self.dataDic setObject:@"0" forKey:@"INSPECT_RESULT"];
                    }else{
                        [cell InspSetBtnType:_dataDic[@"INSPECT_RESULT"]];
                    }
                    
                    cell.clickXsBlock=^{
                        [self.dataDic setObject:@"1" forKey:@"INSPECT_RESULT"];
                    };
                    cell.clickAqBlock=^{
                        [self.dataDic setObject:@"0" forKey:@"INSPECT_RESULT"];
                    };
                    cell.clickPzBlock=^{
                        [self.dataDic setObject:@"2" forKey:@"INSPECT_RESULT"];
                        
                    };
                    return cell;
                    
                }else if(row==4){
                    B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                    
                    cell.textValueChangedBlock=^(NSString *value){
                        [self.dataDic setObject:value forKey:@"INSPECT_DESC"];
                    };
                    
                    [cell setTitle:@"备   注:" andPlaceHolder:@"请输入备注" andTextValue:_dataDic[@"INSPECT_DESC"]];
                    
                    cell.isEdit=weakSelf.isEdit;
                    
                    return cell;
                    
                } else {
                    ScoureCell *cell=[tableView dequeueReusableCellWithIdentifier:@"scoureCell" forIndexPath:indexPath];
                    cell.scoreLimit = self.scoreLimit;
                    cell.view = self.navigationController.view;
                    cell.isEdit=self.isEdit;
                    // 默认100
                    cell.textFile.text = [_dataDic[@"INSPECT_SCORE"] isEqualToString:@""] ? self.scoreLimit : _dataDic[@"INSPECT_SCORE"];
                    
//                    if([_dataDic[@"INSPECT_SCORE"] isEqualToString:@""]){
//                        [self.dataDic setObject:self.scoreLimit forKey:@"INSPECT_SCORE"];
//                    }
                    
//                    cell.textBlock=^(NSString *value){
//                        [self.dataDic setObject:value forKey:@"INSPECT_SCORE"];
//                    };
                    
                    cell.textBlock = ^(NSString *value){
                        self.score = value;
                    };
                    
                    return cell;
                }
            }else{
                if(row==0){
                    DoubleBtnCell *cell=[DoubleBtnCell cellWithTableView:tableView];
                    if([self.flag isEqualToString:@"add"]){
                        cell.routineBtn.selected=YES;
                        cell.edit=YES;
                        cell.extraClickBtn=^(){
                            weakSelf.ipqc=@"extra";
                            weakSelf.scoreLimit = @"5";
                            self.score = nil;
                            [weakSelf.tableView reloadData];
                        };
                        cell.rountine=^(){
                            self.scoreLimit = [LSUtility getInspectScore:_itemId];
                            weakSelf.ipqc=@"routine";
                            self.score = nil;
                            [weakSelf.tableView reloadData];
                        };
                    }else{
                        cell.edit=NO;
                        cell.routineBtn.selected=YES;
                    }
                    return cell;
                    
                }else if(row==1){
                    DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
                    
                    NSString *jiancl=self.dataDic[@"class"];
                    [cell setTitle:@"检 查 类:" andDetail:[jiancl isEqualToString:@""]?@"请选择检查类":jiancl andLeftConstraint:20.];
                    
                    return  cell;
                    
                }else if(row==2){
                    
                    B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                    
                    [cell setTitle:@"检查内容:" andPlaceHolder:@"请选择检查内容" andTextValue:_dataDic[@"itemName"]];
                    //指定检查项 额外检查项
                    //能编辑或者新增
                    if(self.isEdit&&[self.flag isEqualToString:@"add"]){
                        [_btnView addTarget:self action:@selector(clickItem) forControlEvents:UIControlEventTouchUpInside];
                    }
                    _btnView.frame=cell.contentView.bounds;
                    [cell.contentView addSubview:_btnView];
                    
                    cell.isEdit=YES;
                    
                    return cell;
                    
                }else if(row==3){
                    
                    B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                    
                    cell.textValueChangedBlock=^(NSString *value){
                        [self.dataDic setValue:value forKey:@"INSPECT_INFO"];
                    };
                    
                    [cell setTitle:@"检查情况:" andPlaceHolder:@"请输入检查情况" andTextValue:DEFISNUL(self.dataDic[@"INSPECT_INFO"])];
                    
                    cell.isEdit=weakSelf.isEdit;
                    
                    return cell;
                    
                }else if(row==4){
                    
                    selectBtnCell *cell=[tableView dequeueReusableCellWithIdentifier:@"sCell" forIndexPath:indexPath];
                    cell.isEdit=self.isEdit;
                    [cell setTitle:@"结论:" andBtn_1:@"合格" andBtn_2:@"不合格" andBtn_3:@"不涉及"];
                    [cell InspSetBtnType:_dataDic[@"INSPECT_RESULT"]];
                    if(self.isEdit){
                        //默认合格
                        if([_dataDic[@"INSPECT_RESULT"] isEqualToString:@""]){
                            [self.dataDic setObject:@"1" forKey:@"INSPECT_RESULT"];
                            [cell InspSetBtnType:@"1"];
                        }
                        
                    }
                    cell.clickXsBlock=^{
                        [self.dataDic setObject:@"1" forKey:@"INSPECT_RESULT"];
                    };
                    cell.clickAqBlock=^{
                        [self.dataDic setObject:@"0" forKey:@"INSPECT_RESULT"];
                    };
                    cell.clickPzBlock=^{
                        [self.dataDic setObject:@"2" forKey:@"INSPECT_RESULT"];
                    };
                    return cell;
                    
                }else if(row==5){
                    
                    B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                    
                    cell.textValueChangedBlock=^(NSString *value){
                        
                        [self.dataDic setObject:value forKey:@"INSPECT_DESC"];
                    };
                    
                    [cell setTitle:@"备   注:" andPlaceHolder:@"请输入备注" andTextValue:_dataDic[@"INSPECT_DESC"]];
                    
                    cell.isEdit=weakSelf.isEdit;
                    
                    return cell;
                    
                } else {
                    ScoureCell *cell=[tableView dequeueReusableCellWithIdentifier:@"scoureCell" forIndexPath:indexPath];
                    cell.scoreLimit = self.scoreLimit;
                    cell.view = self.navigationController.view;
                    cell.isEdit = self.isEdit;
                    cell.textFile.text = [_dataDic[@"INSPECT_SCORE"] isEqualToString:@""] ? self.scoreLimit : _dataDic[@"INSPECT_SCORE"];
                    
//                    if([_dataDic[@"INSPECT_SCORE"]isEqualToString:@""]){
//                        [self.dataDic setObject:self.scoreLimit forKey:@"INSPECT_SCORE"];
//                    }
                    
//                    cell.textBlock=^(NSString *value){
//                        [self.dataDic setObject:value forKey:@"INSPECT_SCORE"];
//                    };
                    
                    cell.textBlock = ^(NSString *value){
                        self.score = value;
                    };
                    return cell;
                }
            }
        
        }else{
            if(row==0){
                DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
                
                NSString *jiancl=self.dataDic[@"class"];
                if(jiancl){
                    [cell setTitle:@"检 查 类:" andDetail:[jiancl isEqualToString:@""]?@"未知":jiancl andLeftConstraint:20.];
                }else{
                    [cell setTitle:@"检 查 类:" andDetail:@"其它" andLeftConstraint:20.];
                }

                return  cell;
                
            }else if(row==1){
                
                B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                
                [cell setTitle:@"检查内容:" andPlaceHolder:@"请选择检查内容" andTextValue:_dataDic[@"itemName"]];
                //指定检查项 额外检查项
                //能编辑或者新增
                if(self.isEdit&&[self.flag isEqualToString:@"add"]){
                    [_btnView addTarget:self action:@selector(clickItem) forControlEvents:UIControlEventTouchUpInside];
                    _btnView.frame=cell.contentView.bounds;
                    [cell.contentView addSubview:_btnView];
                }
                
                cell.isEdit=NO;
                
                return cell;
                
            }else if(row==2){
                
                B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                
                cell.textValueChangedBlock=^(NSString *value){
                    NSLog(@"value%@",value);
                    [self.dataDic setValue:value forKey:@"INSPECT_INFO"];
                };
                
                [cell setTitle:@"检查情况:" andPlaceHolder:@"请输入检查情况" andTextValue:DEFISNUL(self.dataDic[@"INSPECT_INFO"])];
                
                cell.isEdit=weakSelf.isEdit;
                
                return cell;
                
            }else if(row==3){
                
                selectBtnCell *cell=[tableView dequeueReusableCellWithIdentifier:@"sCell" forIndexPath:indexPath];
                cell.isEdit=self.isEdit;
                [cell setTitle:@"结论:" andBtn_1:@"合格" andBtn_2:@"不合格" andBtn_3:@"不涉及"];
                //默认为合格
                if([_dataDic[@"INSPECT_RESULT"] isEqualToString:@""]){
                    [self.dataDic setObject:@"1" forKey:@"INSPECT_RESULT"];
                    [cell InspSetBtnType:@"1"];
                }else{
                    [cell InspSetBtnType:_dataDic[@"INSPECT_RESULT"]];

                }

                cell.clickXsBlock=^{
                    [self.dataDic setObject:@"1" forKey:@"INSPECT_RESULT"];
                };
                cell.clickAqBlock=^{
                    [self.dataDic setObject:@"0" forKey:@"INSPECT_RESULT"];
                };
                cell.clickPzBlock=^{
                    [self.dataDic setObject:@"2" forKey:@"INSPECT_RESULT"];
                };
                return cell;
                
            }else if(row==4){
                
                B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                
                cell.textValueChangedBlock=^(NSString *value){
                    
                    [self.dataDic setObject:value forKey:@"INSPECT_DESC"];
                };
                
                [cell setTitle:@"备   注:" andPlaceHolder:@"请输入备注" andTextValue:_dataDic[@"INSPECT_DESC"]];
                
                cell.isEdit=weakSelf.isEdit;
                
                return cell;
                
            }else{
                ScoureCell *cell=[tableView dequeueReusableCellWithIdentifier:@"scoureCell" forIndexPath:indexPath];
                cell.scoreLimit = self.scoreLimit;
                cell.view=self.navigationController.view;
                cell.isEdit=self.isEdit;
                cell.textFile.text = [_dataDic[@"INSPECT_SCORE"]isEqualToString:@""]?self.scoreLimit:_dataDic[@"INSPECT_SCORE"];
                
//                cell.textBlock=^(NSString *value){
//                    [self.dataDic setObject:value forKey:@"INSPECT_SCORE"];
//                };
                
                cell.textBlock = ^(NSString *value){
                    self.score = value;
                };
                
                return cell;
            }
        }
    }else{
        H1_ImagesCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_H1_ImagesCell forIndexPath:indexPath];
        cell.isEdit=self.isEdit;
        [cell setTitle:@"附件信息"];
        [cell setTitleColor:[UIColor colorWithRed:0.22 green:0.64 blue:0.59 alpha:1.00]];
        cell.curTweet = _curTweet;
        cell.addPicturesBlock = ^(){
            [weakSelf showActionForPhoto];
        };
        cell.deleteTweetImageBlockUrl= ^(TweetImage *toDelete,NSString *deUrl){
            //移除图片
            [weakSelf.curTweet deleteATweetImage:toDelete];
            //移除数组
            [weakSelf.selectedAssetURLs removeObject:deUrl];
            //图片链接添加至删除数组
            [self.delImageArray addObject:deUrl];
            [weakSelf refresh:nil];
        };
        
        return cell;
    }
}

/*
 *点击方法
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    WEAKSELF
    if(![self.ipqc isEqualToString:@"extra"]){
        if(weakSelf.isEdit&&[self.flag isEqualToString:@"add"]){
            if(indexPath.section==1){
                if(indexPath.row==1){
                    //巡检任务为空 或者 巡检类已选择 可进行巡检类的选择
                    if([_dataDic[@"itemName"]isEqualToString:@""]||![_dataDic[@"class"]isEqualToString:@""]){
                       
                        if(_groupClassArr.count>0){
                            NSNumber *ninit = [NSNumber numberWithInteger:0];
                            NSMutableArray *arr=[NSMutableArray array];
                            for (NSDictionary *dics in _groupClassArr) {
                                [arr addObject:dics[@"INSPECT_NAME"]];
                            }
                            [ActionSheetStringPicker showPickerWithTitle:nil rows:@[arr] initialSelection:@[ninit] doneBlock:^(ActionSheetStringPicker *picker, NSArray * selectedIndex, NSArray *selectedValue) {
                                int iv = [(NSNumber*)[selectedIndex firstObject] intValue];
                                _inspNum = iv;
                                [weakSelf.dataDic setObject:arr[iv] forKey:@"class"];
                                
                                NSIndexPath *index_2=[NSIndexPath indexPathForRow:1 inSection:1];
                                [weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath,index_2] withRowAnimation:UITableViewRowAnimationNone];
                                
                            } cancelBlock:nil origin:self.view];
                        }else{
                            [LSUtility showToastWithMessage:@"无可添加的例行巡检类" inView:self.view Andtime:1.5];
                        }
                        
                    }else{
                        [LSUtility showToastWithMessage:@"请清空巡检情况在进行选择" inView:self.view Andtime:1.];
                    }
                }
            }
        }
    }
}
/*
 *  选择巡检项
 */
- (void)clickItem{
    WEAKSELF
    NSString *itemPer=self.dataDic[@"class"];
    if(![itemPer isEqualToString:@""]){
        NSNumber *ninit = [NSNumber numberWithInteger:0];
        NSMutableArray *arr=[NSMutableArray array];
        for (NSDictionary *dics in _groupClassArr) {
            [arr addObject:dics[@"ID"]];
        }
        //父级巡检项ID
        _perItemId=arr[_inspNum];
        
        NSArray *itemArr=[LSUtility getItemArrByParentID:_perItemId andProcess:self.taskId];
        
        NSMutableArray *ids=[NSMutableArray array];
        NSMutableArray *names=[NSMutableArray array];
        for (NSDictionary *dic in itemArr) {
            [ids addObject:dic[@"id"]];
            [names addObject:dic[@"itemName"]];
        }
        
        if(names.count==0||ids.count==0){
            [ids addObject:@""];
            [names addObject:@"请在PC端新增该类下巡检项"];
        }
        
        [ActionSheetStringPicker showPickerWithTitle:nil rows:@[names] initialSelection:@[ninit] doneBlock:^(ActionSheetStringPicker *picker, NSArray * selectedIndex, NSArray *selectedValue) {
            int iv = [(NSNumber*)[selectedIndex firstObject] intValue];
            [weakSelf.dataDic setObject:names[iv] forKey:@"itemName"];
            //设置巡检项Id
            _itemId = ids[iv];
            
            // 获取分值上限
            self.scoreLimit = [LSUtility getInspectScore:_itemId];
            // 刷新分值
            NSIndexPath *indexPath3 = [NSIndexPath indexPathForRow:6 inSection:1];
            
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:1];
            [weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath, indexPath3] withRowAnimation:UITableViewRowAnimationNone];
            
        } cancelBlock:nil origin:self.view];
        
    }else{
        [LSUtility showToastWithMessage:@"请先选择检查类" inView:self.view Andtime:1];
    }
}

#pragma mark UIActionSheet M

- (void)showActionForPhoto{
    [self.view endEditing:YES];
    //    @weakify(self);
    [[UIActionSheet bk_actionSheetCustomWithTitle:nil buttonTitles:@[@"拍照", @"从相册选择"] destructiveTitle:nil cancelTitle:@"取消" andDidDismissBlock:^(UIActionSheet *sheet, NSInteger index) {
        
        [self photoActionSheet:sheet DismissWithButtonIndex:index];
        
    }] showInView:self.view];
}

- (void)photoActionSheet:(UIActionSheet *)sheet DismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        //拍照
        if (_curTweet.tweetImages.count >= 9) {//照片最多这么多
            kTipAlert(@"最多只可选择9张照片，已经选满了。先去掉一张照片再拍照呗～");
            return;
        }
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = NO;//设置可编辑
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];//进入照相界面
        
    }else if (buttonIndex == 1){
        
        PictureViewController *picCtr=[[PictureViewController alloc]init];
        picCtr.flag=@"file";
        NSMutableArray *array = [self.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
        picCtr.selectedImages=[[NSMutableArray alloc] initWithArray:array];
        picCtr.selectedImageBlock=^(NSMutableArray *array){
            for (NSString *path in array) {
                //添加图片路径到已选数组
                [self.selectedAssetURLs addObject:path];
            }
        };
        [self refresh:nil];
        [self.navigationController pushViewController:picCtr animated:YES];
    }
}

#pragma mark UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    self.curTweet.editImageView = [[EditImageView alloc]initWithImage:image];
    WEAKSELF
    self.curTweet.editImageView.completeBlock = ^(NSString *path) {
        [weakSelf.curTweet addASelectedAssetURL:path];
        [weakSelf.selectedAssetURLs addObject:path];
        [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:2]] withRowAnimation:UITableViewRowAnimationFade];
    };
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark scrollview
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == self.tableView) {
        [self.view endEditing:YES];
    }
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
